package com.thiswhyme.vc.core;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * Created by thiswhyme on 2021-01-18.
 */
public class ApiHandlerMapping extends RequestMappingHandlerMapping {

    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        return buildFrom(AnnotationUtils.findAnnotation(handlerType, ApiVersion.class));
    }

    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        return buildFrom(AnnotationUtils.findAnnotation(method, ApiVersion.class));
    }

    private ApiCondition buildFrom(ApiVersion platform) {
        return platform == null ? getDefaultCondition() :
                new ApiCondition(ApiConverter.convert(platform.value()));
    }

    private ApiCondition getDefaultCondition(){
        return new ApiCondition(ApiConverter.convert(ApiVersionConstant.DEFAULT_VERSION),true);
    }
}
